// 实现这个项目的构建任务

const { src, dest, parallel, series, watch } = require('gulp')

const del = require('del')

const browserSync = require('browser-sync')
const loadPlugins = require('gulp-load-plugins')
//自动加载插件
const plugins = loadPlugins()
//开发服务器
const bs = browserSync.create()

// 模拟数据信息。
const data = {
  menus: [
    {
      name: 'Home',
      icon: 'aperture',
      link: 'index.html'
    },
    {
      name: 'Features',
      link: 'features.html'
    },
    {
      name: 'About',
      link: 'about.html'
    },
    {
      name: 'Contact',
      link: '#',
      children: [
        {
          name: 'Twitter',
          link: 'https://twitter.com/w_zce'
        },
        {
          name: 'About',
          link: 'https://weibo.com/zceme'
        },
        {
          name: 'divider'
        },
        {
          name: 'About',
          link: 'https://github.com/zce'
        }
      ]
    }
  ],
  pkg: require('./package.json'),
  date: new Date()
}

// 清除打包文件
const clean = () => {
  return del(['dist', 'temp'])
}

// js lint
const eslint = () => {
  return src(['src/assets/scripts/*.js'])
  .pipe(plugins.eslint({
    rules: {
      'no-var': 'warn',
    },
    globals: [
        'jQuery',
        '$'
    ],
    envs: [
        'browser'
    ]
  }))
  .pipe(plugins.eslint.format())
}
// sass lint
const sasslint = () => {
  return src(['src/assets/styles/*.scss'])
  .pipe(plugins.sassLint())
  .pipe(plugins.sassLint.format())
  .pipe(plugins.sassLint.failOnError())
}

// 样式编译
const style = () => {
  // 源代码位置   { base: 'src' }保存原始的目录结构
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}
// js文件编译
const script = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}
// html编译
const page = () => {
  return src("src/**/*.html", { base: "src" })
    .pipe(plugins.swig({ data, defaults: { cache: false } }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}
// 图片文件压缩
const image = () => {
  return src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}
// 字体文件压缩
const font = () => {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 其他文件编译：
const extra = () => {
  return src('public/**', { base: 'public' })
    .pipe(dest('dist'))
}
// 热更新开发服务器
const serve = () => {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/**/*.html', page)

  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ], bs.reload)

  bs.init({
    notify: false,
    port: 2080,
    open: true,

    server: {
      baseDir: ['temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}
// 文件引用处理
const useref = () => {
  return src('temp/*.html', { base: 'temp' })
  .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
  .pipe(plugins.if(/\.js$/, plugins.uglify()))
  .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
  .pipe(plugins.if(/\.html$/, plugins.htmlmin({
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true
  })))
  .pipe(dest('dist'))
}

// 语法检查
const lint = parallel(eslint, sasslint)

const compile = parallel(style, script, page)
const develop = series(compile, serve)

// 打包
const build = series(
  clean,
  parallel(
    series(compile, useref),
    image,
    font,
    extra
  )
)

// 开发任务
const start = series(build, serve)

// 部署文件至生产服务器
// npm install gulp gulp-ssh -D

// const gulp = require('gulp')
// const GulpSSH = require('gulp-ssh')

// // eslint-disable-next-line @typescript-eslint/camelcase
// const { APP_ENV, npm_package_name } = process.env;
// const isProduct = APP_ENV === 'production';

// // 需要上传到服务器的路径
// // eslint-disable-next-line @typescript-eslint/camelcase
// const remotePath = `/home/public/docker/main/${npm_package_name}`
// const config = {
//   ssh: { // 正式
//     host: isProduct ? '' : '192.168.31.227',
//     port: isProduct ? 22 : 8822,
//     username: 'root',
//     password: isProduct ? '' : 'a1234567',
//   },
//   remotePath,
//   commands: [
//     // 删除现有文件
//     `rm -rf ${remotePath}`,
//   ],
// }
// const gulpSSH = new GulpSSH({
//   ignoreErrors: false,
//   sshConfig: config.ssh,
// })
// /**
//  * 上传前先删除服务器上现有文件...
//  */
// gulp.task('execSSH', () => {
//   console.log('删除服务器上现有文件...')
//   return gulpSSH.shell(config.commands, { filePath: 'commands.log' })
//   .pipe(gulp.dest('logs'))
// })
// /**
//  * 上传文件到服务器
//  */

// gulp.task('deploy', gulp.series('execSSH', done => {
//   console.log('2s后开始上传文件到服务器...')
//   setTimeout(() => {
//     // eslint-disable-next-line @typescript-eslint/camelcase
//     gulp.src(`./${npm_package_name}/**`)
//     .pipe(gulpSSH.dest(config.remotePath))
//     console.log('上传完毕.....')
//     done();
//   }, 2000)
// }))



module.exports = {
  clean,
  lint,
  develop,
  serve,
  build,
  start
  // deploy
}

